from PyQt5 import QtCore, QtWidgets, QtGui
import sys

widget_header_color = "QHeaderView::section{background:gray;}"


# 调用方法实例化TableWindow 取到其属性tableWidget操作grid部分
class TableWindow(QtWidgets.QMainWindow):
    def __init__(self, title):
        QtWidgets.QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        self.main_widget = QtWidgets.QWidget(self)

        self.dw_table = QtWidgets.QDockWidget(title, self)
        self.dw_table.setFeatures(QtWidgets.QDockWidget.DockWidgetFloatable)
        self.dwc_table = QtWidgets.QWidget()
        self.vl_table = QtWidgets.QVBoxLayout(self.dwc_table)

        self.tableWidget = QtWidgets.QTableWidget(self.main_widget)
        self.tableWidget.horizontalHeader().setStyleSheet(widget_header_color)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(3)
        self.tableWidget.setShowGrid(True)
        self.tableWidget.setMouseTracking(True)
        self.tableWidget.setRowCount(5)
        self.tableWidget.setFrameShape(QtWidgets.QFrame.NoFrame)

        self.vl_table.addWidget(self.tableWidget)
        self.dw_table.setWidget(self.dwc_table)
        self.addDockWidget(QtCore.Qt.TopDockWidgetArea, self.dw_table)
        self.dwc_table.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.dw_table.topLevelChanged.connect(self._floating_statu)  # 监测窗口浮动

    def _floating_statu(self, event):
        if self.dw_table.isFloating():
            self.dwc_table.customContextMenuRequested[QtCore.QPoint].connect(self.right_menu)
        else:
            self.dwc_table.customContextMenuRequested[QtCore.QPoint].disconnect(self.right_menu)

    def right_menu(self, event):
        menu = QtWidgets.QMenu()
        opt1 = menu.addAction("最大化")
        opt2 = menu.addAction("最小化")
        menu.triggered[QtWidgets.QAction].connect(self.processtrigger)
        menu.exec_(QtGui.QCursor.pos())

    def processtrigger(self, q):
        if q.text() == "最大化":
            self.dw_table.showMaximized()
        elif q.text() == "最小化":
            self.dw_table.showMinimized()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    font = QtGui.QFont()
    # font.setBold(True)
    font.setPointSize(11)
    font.setFamily('微软雅黑')
    app.setFont(font)
    myshow = TableWindow("test")
    # myshow.showMaximized()
    myshow.show()
    sys.exit(app.exec())
